package com.joseph.websocket.test;

import com.alibaba.fastjson.JSON;
import com.joseph.websocket.bean.Message;
import com.joseph.websocket.handler.WebSocketHandler;
import com.joseph.websocket.util.CmdEnum;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class WsClient extends WebSocketClient {

    final Timer timer = new Timer();
    String fromId;
    long lastHeartTime = 0;

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketHandler.class);


    public WsClient(URI serverUri,String fromId) {
        super(serverUri);
        this.fromId = fromId;
    }

    final Map<String, Message> dataBuffer = new HashMap<>();

    public void init() {
        setConnectionLostTimeout(0);
        try {
            connectBlocking(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Message hearbeat = new Message();
                hearbeat.setCmd(CmdEnum.HEART.getCode());
                hearbeat.setFromId(fromId);
                send(JSON.toJSONString(hearbeat));
                System.out.println(2);
            }
        }, 2, 5000);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (System.currentTimeMillis() - lastHeartTime > 30 * 1000) {
                    //重连
                }
            }
        }, 0, 3000);
        for (int i = 0; i < 10; i++) {
            Message message = new Message();
            message.setSeqId(fromId + System.currentTimeMillis()); //userId + timestamp
            message.setCmd(CmdEnum.MESSAGE.getCode());
            message.setContent(RandomUtils.nextInt() + "");
            message.setFromId(fromId);
            message.setToId(fromId);
            dataBuffer.put(message.getSeqId(), message);
            send(JSON.toJSONString(message));
            LOGGER.info("send msg to serer {}",  i);
            //Uninterruptibles.sleepUninterruptibly(2000, TimeUnit.MILLISECONDS);
        }
    }

    public static void main(String[] args) throws InterruptedException, URISyntaxException {
        for (int i = 0; i < 1000; i++) {
            WsClient client = new WsClient(new URI("ws://localhost:8087/ws?userId=" + i), i +"");
            client.init();
        }
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("on open");
    }

    @Override
    public void onMessage(String s) {
        if (StringUtils.isEmpty(s)) {
            return;
        }
        Message message = JSON.parseObject(s, Message.class);
        if (message.getCmd() == CmdEnum.ACK.getCode()) {
            dataBuffer.remove(message.getSeqId());
        } else if (message.getCmd() == CmdEnum.HEART.getCode()) {
            //lastHeartTime = message.getMsgTime();
            System.out.println("recv heart resp");
        }
        System.out.println("recv msg from serer :" + s);
    }

    @Override
    public void onClose(int i, String s, boolean b) {

    }

    @Override
    public void onError(Exception e) {

    }
}
